//
//  UserSettingViewController.m
//  Growth
//
//  Created by  on 12-2-8.
//  Copyright (c) 2012年 MEETStudio. All rights reserved.
//

#import "UserSettingViewController.h"
#import "PublicMethodEngine.h"
#import "RegexKitLite.h"
#import "ASIHTTPConnection.h"


static WebConnectionArray *userInfoModify_connection;
static WebConnectionArray *userGravatarModify_connection;
static WebConnectionArray *passwordModify_connection;
static ASIHTTPConnection *userInfo_connection;



@implementation UserSettingViewController

@synthesize bgView;
@synthesize passwordSettingBgView;

@synthesize passwordTextField;

@synthesize userId;

@synthesize birthdayLabel;

@synthesize genderSwitch;
@synthesize gender;

@synthesize emailTextField;
@synthesize phone1TextField;

//camera
@synthesize photoImageView;
@synthesize userInfoDict;


-(void)dealloc{
   
    [activityIndicatorView release];
    
    [bgView release];
    [passwordSettingBgView release];
    
    if (passwordTextField != nil) {
        [passwordTextField release];
    }
    
    [birthdayLabel release];
    
    [genderSwitch release];
    [gender release];
    
    [emailTextField release];
       //camera
    [photoImageView release];
    [userInfoDict release];
    
    if (userGravatarModify_connection != nil) {
        userGravatarModify_connection.connectionDelegate = nil;
        [userGravatarModify_connection release];
        userGravatarModify_connection = nil;
    }
    if (userInfoModify_connection != nil) {
        userInfoModify_connection.connectionDelegate = nil;
        [userInfoModify_connection release];
        userInfoModify_connection = nil;
    }
    if (passwordModify_connection != nil) {
        passwordModify_connection.connectionDelegate = nil;
        [passwordModify_connection release];
        passwordModify_connection = nil;
    }
    if (userInfo_connection != nil) {
        userInfo_connection.connectionDelegate = nil;
        [userInfo_connection release];
        userInfo_connection = nil;
    }
    
    //
    [phone1TextField release];
    [phone2TextField release];
    [mailCodeTextField release];
    [workCompanyTextField release];
    [homeAddresd release];
    
    
    
    [myScrollView release];
    [backGroundButton release];
    
    
     [super dealloc];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark -UITextField delegate

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    curEditTextField =textField;
    
   
}

-(void)textFieldDidEndEditing:(UITextField *)textField{
    
    
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark take photo action

-(IBAction)takePhoto:(id)sender{
    
    UIActionSheet *actionSheet = [[UIActionSheet alloc]init];
    actionSheet.delegate = self;
    actionSheet.tag = 1;
    
    [actionSheet addButtonWithTitle:@"从相册选择"];
    [actionSheet addButtonWithTitle:@"拍照"];
    [actionSheet addButtonWithTitle:@"取消"];
    [actionSheet setCancelButtonIndex:2 ];
    
    [actionSheet showInView:self.view];
    
    
    [actionSheet showFromRect:CGRectMake(0, 480, 320, 40) inView:self.view animated:YES];
    
}


- (IBAction)showCamera:(id)sender
{
	[LoadingView showDefaultLoadingView];
	
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
		
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypeCamera;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
        [imagePickerController setAllowsEditing:YES];
        [self presentModalViewController:imagePickerController animated:YES];
        
        
        [imagePickerController release];
        
		
	}
	else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
		imagePickerController.delegate = self;
        [imagePickerController setAllowsEditing:YES];
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
		
		[self presentModalViewController:imagePickerController animated:YES];
             
		[imagePickerController release];
	}
	else if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
		UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
		imagePickerController.sourceType=UIImagePickerControllerSourceTypeSavedPhotosAlbum;
		imagePickerController.allowsEditing = YES;
		imagePickerController.delegate = self;
		imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
        [self presentModalViewController:imagePickerController animated:YES];
       
		[imagePickerController release];
	}
	
	
}


- (IBAction)showPhotoLibrary:(id)sender
{
	if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
		
		[NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(showPhotoLibrary) userInfo:nil repeats:NO];
	}
	
}

-(void)showPhotoLibrary
{
	UIImagePickerController *imagePickerController=[[UIImagePickerController alloc] init];
	
	imagePickerController.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
	imagePickerController.delegate = self;
	imagePickerController.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
    [self presentModalViewController:imagePickerController animated:YES];
    [imagePickerController release];
}

#pragma mark  Camera
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
	
    //如果是 来自照相机的image，那么先保存
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(image, nil,  nil, nil); 
    }
    
    UIImage *newImage = [[PublicMethodEngine sharedPublicMethodEngine] compresImageWith:image maxPix:PHOTO_MAXPIX];
    
    isPhotoChange = YES;
	photoImageView.image=newImage;
   	
	[picker dismissModalViewControllerAnimated:NO];
	
    [newImage release];
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	
	
	[picker dismissModalViewControllerAnimated:NO];
	
	[self.view setFrame:CGRectMake(0, 0, 320, 480)];
}

#pragma mark UINavigationControllerDelegate
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
	CLog(@"willshow");
	
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
	CLog(@"didshow");
    [LoadingView hideWithAnimated:YES];
}

-(void)addSomeElements:(UIViewController *)viewController{
	//Add the motion view here, PLCameraView and picker.view are both OK
	UIView *PLCameraView=[self findView:viewController.view withName:@"PLCameraView"];
	
	//Get Bottom Bar
	UIView *bottomBar=[self findView:PLCameraView withName:@"PLCropOverlayBottomBar"];
	
	//Get ImageView For Save
	UIImageView *bottomBarImageForSave = [bottomBar.subviews objectAtIndex:0];
	
	//Get Button 0
	UIButton *retakeButton=[bottomBarImageForSave.subviews objectAtIndex:0];
	[retakeButton addTarget:self action:@selector(showLibraryButton) forControlEvents:UIControlEventTouchUpInside];
	
	//Get ImageView For Camera
	UIImageView *bottomBarImageForCamera = [bottomBar.subviews objectAtIndex:1];
	
	//Get Button 0(The Capture Button)
	UIButton *cameraButton=[bottomBarImageForCamera.subviews objectAtIndex:0];
	[cameraButton addTarget:self action:@selector(hideLibraryButton) forControlEvents:UIControlEventTouchUpInside];
	
}
//Find the view we want in camera structure.
-(UIView *)findView:(UIView *)aView withName:(NSString *)name{
	Class cl = [aView class];
	NSString *desc = [cl description];
	
	if ([name isEqualToString:desc])
		return aView;
	
	for (NSUInteger i = 0; i < [aView.subviews count]; i++)
	{
		UIView *subView = [aView.subviews objectAtIndex:i];
		subView = [self findView:subView withName:name];
		if (subView)
			return subView;
	}
	return nil;	
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    
   
    UIButton *rightBt = [[UIButton alloc]initWithFrame:CGRectMake(0, 7, 50, 30)];
    [rightBt.titleLabel setFont:[UIFont systemFontOfSize:17]];
    [rightBt.titleLabel setTextColor:[UIColor whiteColor]];
    [rightBt setTitle:@"保存" forState:UIControlStateNormal];
    [rightBt addTarget:self action:@selector(postUserModify:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:rightBt];
    [self.navigationItem setRightBarButtonItem:rightButton];
    [rightBt release];
    [rightButton release];

    
    [myScrollView setContentSize:CGSizeMake(320, 550)];
       
    passwordSettingBgView.layer.cornerRadius = 3;
    passwordSettingBgView.layer.shadowOpacity = 0.4;
	passwordSettingBgView.layer.shadowRadius = 1.5;
	passwordSettingBgView.layer.shadowOffset = CGSizeMake(0, 0);
       
    
    photoImageView.layer.cornerRadius = 3;
    photoImageView.clipsToBounds = YES;
       
    self.navigationItem.title = @"个人信息";
    isPhotoChange = NO;
    
    genderSwitch.onText = @"男";
    genderSwitch.offText = @"女";
    
    photoImageView.layer.cornerRadius = 3;
    [photoImageView setClipsToBounds:YES];
    
    [super viewDidLoad];
    
    self.userId = [[[NSUserDefaults standardUserDefaults] valueForKey:@"userId"] intValue];

    [self loadUserInfoData];
   
    
    
    //初始化昵称、头像基本信息
    NSString *attachmendId = [[NSUserDefaults standardUserDefaults] valueForKey:@"userAttachmentId"];
    
    if (![attachmendId isMemberOfClass:[NSNull class]]) {
        NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",UCENTERBASEURL,@"/gravatar", attachmendId];
        NSURL *url = [NSURL URLWithString:string];	
        CLog(@"gravatar url %@", url);
        [self.photoImageView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"doctorPhoto.jpg"] imageType:kImageCache_Content_Icon];
    }

   NSString *userName =  [[NSUserDefaults standardUserDefaults] valueForKey:@"userName"];

    if(self){
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillShow:)
													 name:UIKeyboardWillShowNotification
												   object:nil];
		
		[[NSNotificationCenter defaultCenter] addObserver:self
												 selector:@selector(keyboardWillHide:)
													 name:UIKeyboardWillHideNotification
												   object:nil];
	}
    

    
    // Do any additional setup after loading the view from its nib.
}


- (void)loadUserInfoView
{
    //头像
    NSString *userNickname = [userInfoDict objectForKey:@"Nickname"];
    NSString *email = [userInfoDict objectForKey:@"PrivateEmail"];
    NSString *phone1 = [userInfoDict objectForKey:@"Mobile"] ;
    NSString *phone2 = [userInfoDict objectForKey:@"Mobile"] ;
  //  NSString *attachmendId = [userInfoDict objectForKey:@"userAttachmentId"];
    NSString *genderStr = [userInfoDict objectForKey:@"Gender"];
    NSString *birthdate = [userInfoDict objectForKey:@"Birthday"];
    NSString *post_Pode = [userInfoDict objectForKey:@"CardID"];
    NSString *work_Unit = [userInfoDict objectForKey:@"CommunityID"];
    NSString *home_Pddr = [userInfoDict objectForKey:@"Title"];
    
   
    
    if (![email isMemberOfClass:[NSNull class]]) {
        emailTextField.text = email;
        emailTextField.enabled = NO;
        emailTextField.textColor = [UIColor grayColor];
    }
    
    if (![phone1 isMemberOfClass:[NSNull class]]) {
        phone1TextField.text = phone1;
        phone1TextField.enabled = YES;
        phone1TextField.textColor = [UIColor grayColor];
    }
    if (![phone2  isMemberOfClass:[NSNull class]]) {
        phone2TextField.text = phone2;
        phone2TextField.enabled = YES;
        phone2TextField.textColor = [UIColor grayColor];
    }

    
    if (![genderStr isMemberOfClass:[NSNull class]]) {
        gender = genderStr;
        if ([genderStr intValue]) {
            [genderSwitch setOn:NO animated:NO];
        }
        else {
            [genderSwitch setOn:YES animated:NO];
        }
    }
    else {
        gender = @"1";
        [genderSwitch setOn:NO animated:NO];
    }
    
    if (![birthdate isMemberOfClass:[NSNull class]]) {
        
        birthdayLabel.text = birthdate;
        birthdayLabel.textColor = [UIColor blackColor];
    }
    
    if (![post_Pode isMemberOfClass:[NSNull class]]) {
        mailCodeTextField.text = post_Pode;
    }
    
    if (![work_Unit isMemberOfClass:[NSNull class]]) {
        workCompanyTextField.text = work_Unit;
    }
    if (![home_Pddr isMemberOfClass:[NSNull class]]) {
         homeAddresd.text = home_Pddr;
    }
    if (![userNickname isMemberOfClass:[NSNull class]]) {
        nameField.text = userNickname;
    }

    
//    if (![attachmendId isMemberOfClass:[NSNull class]]) {
//        NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",UCENTERBASEURL,@"/gravatar", attachmendId];
//        NSURL *url = [NSURL URLWithString:string];	
//        CLog(@"gravatar url %@", url);
//        [self.photoImageView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"geren_set_iphone.png"] imageType:kImageCache_Content_Icon];
//    }

    
}

#pragma  mark load data
-(void)loadUserInfoData{
    
    activityIndicatorView.hidden = NO;
    [activityIndicatorView  startAnimating ];
   
    NSString *LoginUser_ID = [[NSUserDefaults standardUserDefaults] valueForKey:USER_ID];
    
    NSString *urlString = [NSString stringWithFormat:@"%@/MobileUser/DisplayProfileAction.aspx?UserID=%@",BASEURL,LoginUser_ID];
	NSURL *url = [NSURL URLWithString:urlString];
    
    if (userInfo_connection != nil) {
        userInfo_connection.connectionDelegate = nil;
        [userInfo_connection release];
        userInfo_connection = nil;
    }
    
    userInfo_connection = [[ASIHTTPConnection alloc] initGETWithURL:url resultDict:YES isCache:YES];
    userInfo_connection.connectionDelegate = self;
    
    [userInfo_connection startAsynchronous];
    
}

#pragma mark connectino delegate
- (void)requestFinished:(ASIHTTPConnection *)connection resultDict:(NSDictionary *)dict URL:(NSURL *)url info:(NSDictionary *)info{
    
    CLog(@"userInfoDict = %@",dict);
    
    if (self.userInfoDict != nil) {
        [self.userInfoDict release];
    }
    
    NSArray *array = [dict objectForKey:@"datalist"];
    
    if (array != nil && array.count > 0) {
        
        self.userInfoDict = [[NSDictionary alloc]initWithDictionary:[array objectAtIndex:0]];
        
        
        [self loadUserInfoView];

    }
    
    [LoadingView hideWithAnimated:YES];
    
}

- (void)requestFailed:(ASIHTTPConnection *)connection error:(NSError *)error URL:(NSURL *)url info:(NSDictionary *)info{
     [LoadingView hideWithAnimated:YES];
    
}

#pragma mark connection delegate
- (void)connectionSuccess:(NSDictionary *)dict{
	
    CLog(@"user info dict %@", dict);
    
    activityIndicatorView.hidden = YES;
    [activityIndicatorView stopAnimating];
    
    NSString *userIdStr = [dict objectForKey:@"userId"];
    if (![userIdStr isMemberOfClass:[NSNull class]] && [userIdStr intValue] == userId) {
        if (self.userInfoDict != nil) {
            [self.userInfoDict release];
        }
        
        self.userInfoDict = [dict objectForKey:@"patientinfo"];
   

        [self loadUserInfoView];
         [LoadingView hideWithAnimated:YES];
    }
    else {
        [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"用户信息获取错误,请重试" duration:DEFAULT_LOADING_TIME];

    }
    


   
}

- (void)connectionError:(NSError *)error{
    
    activityIndicatorView.hidden = YES;
    [activityIndicatorView stopAnimating];
    
     [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];
    
	CLog(@"error info");
}

- (void)postSuccess:(NSString *)postinfo{
    CLog(@"post info");
    
    
}




- (void)connectionArraySuccess:(NSDictionary *)dict connectionURL:(NSString *)url{
    
    [LoadingView hideWithAnimated:YES];
    
    if ([dict isMemberOfClass:[NSNull class]]) {
        return;
    }
    
    CLog(@"Modify dict %@", dict);
    
    NSRange range = [url rangeOfString:@"user/profile/modify"];
    
    if (range.length >0) {
        _isPostModify = NO;
        
        NSDictionary *backDict = [dict objectForKey:@"object"];
        
        if (![backDict isMemberOfClass:[NSNull class]] && [[backDict objectForKey:@"errorCode"] intValue] == 0) {
            
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"保存信息成功" ];
            
            
            return;
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"保存信息失败" ];  
            
            
            return;
        }

    }
    
    range = [url rangeOfString:@"gravatar/modify"];
    
    if (range.length >0) {
        NSDictionary *backDict = [dict objectForKey:@"object"];
        
        if (![backDict isMemberOfClass:[NSNull class]] && [[backDict objectForKey:@"errorCode"] intValue] == 0) {
            
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"保存头像成功" ];
            
            NSString *newAttachmentId = [backDict objectForKey:@"userAttachmentId"];
            [[NSUserDefaults standardUserDefaults] setValue:newAttachmentId forKey:@"userAttachmentId"];
            
            NSString *string=[NSString stringWithFormat:@"%@%@/%@/100x100",UCENTERBASEURL,@"/gravatar", newAttachmentId];
            NSURL *url = [NSURL URLWithString:string];	
            
            [self.photoImageView setImageWithURL:url refreshCache:NO placeholderImage:[UIImage imageNamed:@"doctorPhoto.jpg"] imageType:kImageCache_Content_Icon];
            
            isPhotoChange = NO;
            return;
        }
        else {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"保存头像失败" ];  
            isPhotoChange = YES;
            return;
        }
        
    }
    
    
    range = [url rangeOfString:@"password/modify"];
    if(range.length > 0){
        CLog(@"password modify result %@", dict);
        NSDictionary *objectDict = [dict objectForKey:@"object"];
        NSNumber *errorCode = [objectDict objectForKey:@"errorCode"];
        if (![errorCode isMemberOfClass:[NSNull class]] && [errorCode intValue] == 0) {
            [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"密码设置成功！"];
            
            [[NSUserDefaults standardUserDefaults] setValue:@"0" forKey:REGIST_LOGIN_KEY];
            
        }
        else {
            [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"密码设置出错，请重试" duration:DEFAULT_LOADING_TIME];
        }
        
    }
    
    CLog(@"content success!");
    
    
}

- (void)connectionArrayError:(NSError *)error{
    
    
    [LoadingView showImage:[UIImage imageNamed:@"wangluo_iphone.png"] info:@"网络请求错误或超时！" duration:DEFAULT_LOADING_TIME *1.2];   
    
    
}
-(void)postUserModify:(id)sender{
    
    [emailTextField resignFirstResponder];
    [phone1TextField resignFirstResponder];
              
    
    NSString *email = nil;
    NSString *phone = nil;
    NSString *birthdate = nil;
    
    NSMutableArray *keys = [[[NSMutableArray alloc] init] autorelease];
    NSMutableArray *values = [[[NSMutableArray alloc] init] autorelease];
    
    CLog(@"Email %@", emailTextField.text);
    if (![emailTextField.text isEqualToString:@""] && emailTextField.text != nil) {
        email = emailTextField.text;
        
        BOOL isEmail = [email isMatchedByRegex:REGEX_EMAIL];
        
        CLog(@" Post invite email!  ************ %d", isEmail);
        if (!isEmail) {
            
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"邮箱错误" message:@"邮箱格式是不是输错啦！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
            return;
        }
        else {
            [keys addObject:@"PrivateEmail"];
            [values addObject:email];
        }
    }
    
    CLog(@"Phone %@", phone1TextField.text);
    
   
        phone = phone1TextField.text;
        
        BOOL isphone = [phone isMatchedByRegex:REGEX_PHONE];
        CLog(@" Post invite phone!  ************ %d", isphone);
        
        if (!isphone)
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"输入有误" message:@"请确认您输入的手机号正确！" 
                                                           delegate:self 
                                                  cancelButtonTitle:@"确定" otherButtonTitles:nil];
            
            [alert show];
            [alert release];
            
            return;
        }
        else {
            [keys addObject:@"Mobile"];
            [values addObject:phone];
        }
   
    
    if (birthdayLabel.textColor != [UIColor grayColor]) {
        birthdate = birthdayLabel.text;
        
//        NSTimeInterval t = [[self dateFromString:birthdate] timeIntervalSince1970];
//        long long  int birthdate_long  = (long long int)t*1000;
        
        [keys addObject:@"Birthday"];
        [values addObject:birthdate];
    }
    
    int uid = [[[NSUserDefaults standardUserDefaults] valueForKey:USER_ID] intValue];
    [keys addObject:@"UserID"];
    [values addObject:[NSNumber numberWithInt:uid]];
    
    
    [keys addObject:@"Nickname"];
    [values addObject:nameField.text];
    
    [keys addObject:@"Title"];
    [values addObject:homeAddresd.text];
    
    [keys addObject:@"CardID"];
    [values addObject:mailCodeTextField.text];
    
   
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:values forKeys:keys];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    CLog(@"theBodyString  %@", theBodyString);
    
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest * request = [WebRequest userInfoModifyRequestWith:jsonData];
    
    CLog(@"request %@", request);
    if (userInfoModify_connection != nil) {
        userInfoModify_connection.connectionDelegate = nil;
    }
    userInfoModify_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
    
    _isPostModify = YES;  

    [self postUserIcon];
    
}

- (void)postUserIcon
{
    
    if(isPhotoChange){  //修改了头像
        //base64编码 图片
        
        if(photoImageView.image){
            NSNumber *uid = [NSNumber numberWithInt:self.userId];
            NSString *imageString = [Photo image2String:photoImageView.image];
            NSString *imageName = @"userIcon";
            
            NSArray *keyArray = [NSArray arrayWithObjects:@"uid", @"fileData", @"fileName", nil];
            NSArray *valueArray = [NSArray arrayWithObjects:uid, imageString, imageName, nil];
            
            
            
            NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
            
            NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
            CLog(@"theBodyString  %@", theBodyString);
            NSData *postJsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
            
            NSMutableURLRequest * request = [WebRequest userGravatarModifyRequestWith:postJsonData];
            
            CLog(@"request %@", request);
            if (userGravatarModify_connection != nil) {
                userGravatarModify_connection.connectionDelegate = nil;
            }
            userGravatarModify_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
            
            _isPostUserIcon = YES;
            
        }
        
    } 
}


- (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat: @"yyyy-MM-dd"]; 
    
    
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    
    
    
    [dateFormatter release];
    
    return destDate;
    
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}



-(IBAction)backGoundTap:(id)sender{
    
}


#pragma mark - Acttion

- (IBAction)genderChangeAction:(id)sender
{
    if (genderSwitch.isOn) {
        gender = @"0";
    }
    else {
        gender = @"1";
    }
    
    CLog(@"Gender change");
}


-(IBAction)selectTimeValue:(id)sender
{
    //已有宝宝不准修改
    
    NSString *title = UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation) ? @"\n\n\n\n\n\n\n\n\n" : @"\n\n\n\n\n\n\n\n\n\n\n\n" ;
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"确定", @"取消",nil];
    
    [actionSheet setCancelButtonIndex:1];
    
    [actionSheet showInView:self.view];
    UIDatePicker *datePicker = [[[UIDatePicker alloc] init] autorelease];
    datePicker.tag = 101;
    datePicker.datePickerMode = 1;
    if (birthdayLabel.textColor == [UIColor blackColor]) {
        NSString *birthdayStr = birthdayLabel.text;
        birthdayStr = [birthdayStr stringByAppendingString:@" 12:00:00"];
        NSDate *birthdayDate = [[PublicMethodEngine sharedPublicMethodEngine] NSStringDateToNSDate:birthdayStr];
        
        CLog(@"date str:%@, date:%@", birthdayStr, birthdayDate);
        
        if (birthdayDate != nil) {
            datePicker.date = birthdayDate;
        }
        
    }
    // [datePicker setMaximumDate:[NSData data]];
    [actionSheet addSubview:datePicker];
    [actionSheet showFromRect:CGRectMake(0, 480, 320, 40) inView:self.view animated:YES];
    actionSheet.tag = 110;
    //  [actionSheet showFromTabBar:(UITabBar *)self.tabBarController.view];     
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (actionSheet.tag == 1) {
        if (buttonIndex == 0) {
            
            [self showPhotoLibrary:nil];        
            
        }
        if (buttonIndex == 1) {
            
            [self showCamera:nil];
            
        }
        
    }
    else if(actionSheet.tag = 110){
        switch (buttonIndex) {
            case 0:
            {
                UIDatePicker *datePicker = (UIDatePicker *)[actionSheet viewWithTag:101];
                NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
                formatter.dateFormat = @"yyyy-MM-dd";
                NSString *timesp = [formatter stringFromDate:datePicker.date];
                
                birthdayLabel.text =timesp;
                birthdayLabel.textColor = [UIColor blackColor];
                break;
            }
            case 1:
            {
                
            }
            default:
                break;
        }
    }
    
    
    
    [actionSheet release];
} 



-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView  
{  
    //该方法来自协议<UIPickerViewDataSource>  
    //该方法用来确定pickerView有几个component;  
    //我们只创造一个component，只需要返回1就行了  
    return 1;  
    
}  


#pragma mark - 密码修改

- (IBAction)passwordSettingAction:(id)sender
{          
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请输入密码！\n\n"
                                                   delegate:self 
                                          cancelButtonTitle:nil otherButtonTitles:nil];
    
    [alert addButtonWithTitle:@"取消"];
    [alert addButtonWithTitle:@"确定"];
    
    [alert setCancelButtonIndex:0];
    
    if (passwordTextField == nil) {
        passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 40.0, 260.0, 26.0)];
        passwordTextField.delegate = self;
        [passwordTextField setBackgroundColor:[UIColor whiteColor]];
        [passwordTextField setBorderStyle:UITextBorderStyleRoundedRect];
        [passwordTextField setPlaceholder:@"请输入密码"];
        [passwordTextField setSecureTextEntry:YES];
        
    }
    
    passwordTextField.text = nil;
    
    [alert addSubview:passwordTextField];
    
    
    alert.tag = 110;
    
    
    [alert show];
    [alert release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 110) {
        
        if (buttonIndex == 0) {
            return;
        }
        else {
            NSString *password = passwordTextField.text;
            CLog(@"password %@", password);
            
            
            if (password != nil && password.length >0) {
                [self passwordModifyWith:password];
            }
            else {
                [LoadingView showDurationMessageLoadingViewWith:DEFAULT_LOADING_TIME message:@"密码不能为空！"];
            }
            
        }
        
        
        
    }
    
}


- (IBAction)backGroundTap{
    
    [emailTextField resignFirstResponder];
    [phone1TextField resignFirstResponder];
    [phone2TextField resignFirstResponder];
    [mailCodeTextField resignFirstResponder];
    [homeAddresd resignFirstResponder];

    [workCompanyTextField resignFirstResponder];

}

-(void) keyboardWillShow:(NSNotification *)note{
    // get keyboard size and loctaion
	CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue: &keyboardBounds];
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    
    // Need to translate the bounds to account for rotation.
    keyboardBounds = [self.view convertRect:keyboardBounds toView:nil];
    
	// get a rect for the textView frame
	CGRect containerFrame = myScrollView.frame;
    // containerFrame.origin.y = self.view.bounds.size.height - (keyboardBounds.size.height + containerFrame.size.height);
    
    
    containerFrame.origin.y = CGRectGetHeight(myScrollView.frame) - (keyboardBounds.size.height + containerFrame.size.height -10);
    
    if (curEditTextField == phone1TextField) {
        
        containerFrame.origin.y += 50;
        
    }
    
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
	
	// set views with new info
	myScrollView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGround button
    
    backGroundButton.hidden = NO;
    
    
}

-(void) keyboardWillHide:(NSNotification *)note{
    NSNumber *duration = [note.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSNumber *curve = [note.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey];
	
	// get a rect for the textView frame
	CGRect containerFrame = myScrollView.frame;
    containerFrame.origin.y = 0;
    
    // containerFrame.origin.y = 380;
	
	// animations settings
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:[duration doubleValue]];
    [UIView setAnimationCurve:[curve intValue]];
    
	// set views with new info
	myScrollView.frame = containerFrame;
	
	// commit animations
	[UIView commitAnimations];
    
    //backGroundButton
    backGroundButton.hidden = YES;
}



#pragma mark - Password Setting
- (void)passwordModifyWith:(NSString *)passWord
{
    
    NSString *userIdStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"];
    
    NSArray *valueArray = [NSArray arrayWithObjects:userIdStr, passWord, nil];
    
    NSArray *keyArray = [NSArray arrayWithObjects:@"uid", @"password", nil];
    
    NSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    
    NSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];
    
    NSData *jsonData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableURLRequest *request = [WebRequest passwordModifyRequestWith:jsonData] ;
    
    CLog(@"request %@", request);
    if (passwordModify_connection != nil) {
        passwordModify_connection.connectionDelegate = nil;
    }
    passwordModify_connection = [[WebConnectionArray alloc] initWith:request delegate:self dataBaseListName:nil];
}

@end
